package Login;

import java.awt.CardLayout;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.Timer;

import niso.DBHandler;
import niso.userFrame;
import niso.User;

public class LoginPane extends JPanel implements ActionListener, MouseListener, MouseMotionListener {
	private CardLayout cards;
	private int curFrame;
	private JPanel parent;
	private BufferedImage bg;
	private Button back, login;
	private Timer time;
	private DBHandler db;
	private User tempUser;
	private JTextField username;
	private JPasswordField pass;
	private ArrayList<User> users;
	private boolean corPass, corUsrName, started;
	private JFrame frame;
	
	public LoginPane(JPanel parent, int n, CardLayout cards, String filename, JFrame frame){
		this.frame=frame;
		this.cards=cards;
		this.curFrame=n;
		this.parent=parent;
		this.setLayout(null);
		corPass=false;
		corUsrName=false;
		tempUser= new User("","","");
		db = new DBHandler(3306, "nisodb", "root", "p@ssword");
		back =  new Button("images/back.png", "images/back2.png", "images/back2a.png");
		login = new Button("images/l"+n+".png", "images/l"+n+"a.png", "images/l"+n+".png");
		
		try {
			this.bg=ImageIO.read(new File(filename));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.print("Image not found");
			e.printStackTrace();
		}
		time = new Timer(300, this);
		this.addMouseListener(this);
		this.addMouseMotionListener(this);
		
		JLabel usrname = new JLabel("Username:");
		JLabel passwrd = new JLabel("Password:");
		username = new JTextField();
		pass =new JPasswordField();
		
		
		Font font = new Font("Calibri", Font.PLAIN, 20);
		usrname.setBounds(240, 115, 165, 27);
	    passwrd.setBounds(240, 175, 165, 27);
		
	    usrname.setFont(font);
	    passwrd.setFont(font);
	    
	    username.setBounds(250, 145, 190, 27);
        pass.setBounds(250, 205, 190, 27);
        
        LoginAL lAL = new LoginAL();
        username.addActionListener(lAL);
        username.addKeyListener(lAL);
        pass.addActionListener(lAL);
		pass.addKeyListener(lAL);
        this.add(usrname);
		this.add(passwrd);
		this.add(username);
		this.add(pass);
		this.getUser();
	}
	
	@Override
	public void actionPerformed(ActionEvent e) {
		repaint();
	}
	public void paint(Graphics g){
		super.paint(g);
		Graphics2D g2D = (Graphics2D)g;

		time.start();
		g2D.drawImage(bg, 25, 60, null);
		g2D.drawImage(back.getCurImg(), 10, 10, null);
		g2D.drawImage(login.getCurImg(), 324, 308, null);
		
		if((!corPass||!corUsrName)&&started){
			Font font = new Font("Calibri", Font.PLAIN, 20);
			g2D.setColor(Color.RED);
			g2D.setFont(font);
			g2D.drawString("   *Error: Wrong username",228, 50);
			g2D.drawString("              or password",228, 72);
			
		}
	}
	public User getUserInfo(){
		return tempUser;
	}
	public boolean isLogin(){
		if((!corPass||!corUsrName)&&started)
			return false;
		else
			return true;
	}
	 
	public  ArrayList<User> getUser(){
		
		users = new ArrayList<User>();
		ResultSet RS;
		
		try {
			RS=db.MySQLSelect("SELECT * from UserAccount");
			switch (curFrame){
				case 3: RS=db.MySQLSelect("SELECT * from UserAccount where Usertype=\"BookKeeper\"");
						tempUser.changeUserType("BookKeeper");
						break;
				case 4:	RS=db.MySQLSelect("SELECT * from UserAccount where Usertype=\"Owner\"");
						tempUser.changeUserType("Owner");
						break;
				case 5: RS=db.MySQLSelect("SELECT * from UserAccount where Usertype=\"Manager\"");
						tempUser.changeUserType("Manager");
						break;
			}
			

			while(RS.next()){
				User temp = new User("", "", "");
				temp.reNameUser(RS.getString("username"));
				temp.changePassword(RS.getString("password"));
				temp.changeUserType(RS.getString(3));
				users.add(temp);
			}	
				RS.close();
			
		}catch(Exception ex){
			
		}
		return users;
	}
	
	
	
	public boolean checkUserName(String username, ArrayList<User> dbUsers){
		
		for(int i=0; i<users.size();i++){
			if(dbUsers.get(i).getUserName().equals(username))
					return true;
			
		}
		return false;
	}
	
	
	public boolean checkPassword(String password,  ArrayList<User> dbPass){
		
		for(int i=0; i<users.size();i++){
			if(dbPass.get(i).getUserPassword().equals(password))
				return true;
			}
		return false;
	}
	
	public boolean validateUser(User U, ArrayList<User> dbPass){
		for(int i=0; i<users.size();i++){
			if(dbPass.get(i).getUserName().equals(U.getUserName())&&dbPass.get(i).getUserPassword().equals(U.getUserPassword()))
				return true;
			}
		return false;
	}
	
	public void login(){

		/*
		 * Insecure
		 * Correct password may work for the wrong user
		 * 
		 * */
		//corPass=checkUserName(tempUser.getUserName(), users);
		//corUsrName=checkPassword(tempUser.getUserPassword(), users);
		started=true;
		
		if(validateUser(tempUser,users)){
		//if(corPass&&corUsrName){
			DBHandler DBH=new DBHandler(3306, "NisoDB", "root", "p@ssword");
			userFrame UFrame=new userFrame(tempUser, DBH);
			
			System.out.println("type: "+tempUser.getusertype());
			//new UserMain(curFrame, tempUser.getUserName(), users);
			frame.dispose();
		}
	}
		
	@Override
	public void mouseDragged(MouseEvent m) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseMoved(MouseEvent m) {
		// TODO Auto-generated method stub
		if (m.getX() >= 12&& m.getX()<=102&&m.getY()>=11&&m.getY()<=42){//within the boundaries of back
			back.setCurImg(1);
			
		}
		else if (m.getX() >= 325&& m.getX()<=460&&m.getY()>=311&&m.getY()<=351){//within the boundaries of login
			login.setCurImg(1);
		}
		else{
			back.setCurImg(0);
			login.setCurImg(0);
		}
	}

	@Override
	public void mouseClicked(MouseEvent m) {
		// TODO Auto-generated method stub
		if (m.getX() >= 12&& m.getX()<=102&&m.getY()>=11&&m.getY()<=42){//within the boundaries of back
			switch(curFrame){
			
			case 3:  cards.show(parent, curFrame-1+"");break;
			case 4:  cards.show(parent, curFrame-2+"");break;
			case 5:  cards.show(parent, curFrame-3+"");break;
			
			}
			back.setCurImg(0);
			}
		else if (m.getX() >= 325&& m.getX()<=460&&m.getY()>=311&&m.getY()<=351){//within the boundaries of login
			tempUser.changePassword(pass.getText());
			tempUser.reNameUser(username.getText());
			
			login();
		}
	}
	@Override
	public void mouseEntered(MouseEvent m) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseExited(MouseEvent m) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mousePressed(MouseEvent m) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void mouseReleased(MouseEvent m) {
		// TODO Auto-generated method stub
		
	}
	class LoginAL implements ActionListener, KeyListener{

		@Override
		public void actionPerformed(ActionEvent key) {
			// TODO Auto-generated method stub
			tempUser.changePassword(pass.getText());
			tempUser.reNameUser(username.getText());
			
		}

		@Override
		public void keyPressed(KeyEvent key) {
			// TODO Auto-generated method stub

			if (key.getSource()==username&&(key.getKeyCode()==KeyEvent.VK_ENTER||key.getKeyCode()==KeyEvent.VK_TAB)){
				pass.requestFocus();
			}
			else if(key.getSource()==pass&&(key.getKeyCode()==KeyEvent.VK_ENTER||key.getKeyCode()==KeyEvent.VK_TAB)){
				tempUser.reNameUser(username.getText());
				tempUser.changePassword(pass.getText());
				//tempUser.changeUserType(t)
				login();
			}
		}

		@Override
		public void keyReleased(KeyEvent key) {
			// TODO Auto-generated method stub
			
		}

		@Override
		public void keyTyped(KeyEvent key) {
			// TODO Auto-generated method stub
			
		}
	}
}	
	

